<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item
            :to="{ name: 'MatchList' }"
            class="breadcrumb_active_item"
            >赛事管理</el-breadcrumb-item
          >
          <el-breadcrumb-item class="breadcrumb_active_item"
            ><span style="cursor: pointer">
              {{ matchtitle }}
            </span></el-breadcrumb-item
          >
          <el-breadcrumb-item>权限区域管理</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="area_manager_content">
        <!-- 按钮栏 -->
        <el-row>
          <el-col :span="24">
            <div class="area_manager_top">
              <el-button
                size="mini"
                type="primary"
                @click="addFn()"
                v-if="userType == 0"
                >新增</el-button
              >
            </div>
          </el-col>
        </el-row>
        <!-- 数据列表 -->
        <div v-if="areaListData != undefined && areaListData.length > 0">
          <el-row>
            <el-col :span="24">
              <el-table
                :data="areaListData"
                border
                size="mini"
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                >
                </el-table-column>

                <el-table-column
                  prop="area_name"
                  label="权限区域名称"
                  min-width="250"
                  align="center"
                ></el-table-column>

                <el-table-column
                  label="权限区域图标"
                  width="200"
                  align="center"
                >
                  <template slot-scope="scope">
                    <img
                      v-if="scope.row.area_icon"
                      :src="scope.row.area_icon"
                      class="area_icon"
                    />
                  </template>
                </el-table-column>

                <!-- <el-table-column
                  prop="area_mark"
                  label="权限区域值"
                  min-width="140"
                  align="center"
                ></el-table-column> -->

                <el-table-column
                  prop="sequence"
                  label="顺序"
                  min-width="100"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="created_at"
                  label="创建时间"
                  min-width="200"
                  align="center"
                ></el-table-column>

                <el-table-column label="操作" width="260" align="center">
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="primary"
                      @click="detailFn(scope.$index, scope.row)"
                    >
                      查看
                    </el-button>

                    <el-button
                      size="mini"
                      type="primary"
                      v-if="userType == 0"
                      @click="editFn(scope.$index, scope.row)"
                    >
                      编辑
                    </el-button>

                    <el-button
                      size="mini"
                      type="danger"
                      v-if="userType == 0"
                      @click="deleteFn(scope.$index, scope.row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="area_manager_pagination">
                <el-pagination
                  @size-change="listSizeChange"
                  @current-change="listCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="pageSizes"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                >
                </el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row v-else>
          <el-empty description="暂无数据"></el-empty>
        </el-row>
        <!-- 弹窗 -->
        <el-dialog
          :title="dialogTitle"
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
          width="400px"
        >
          <el-form
            ref="dialogDetailForm"
            :model="detailFormData"
            :rules="detailFormRules"
            :disabled="dialogBtnKey == 3"
          >
            <el-form-item
              label="权限区域名称"
              prop="area_name"
              :label-width="formLabelWidth"
            >
              <el-input
                size="small"
                style="width: 200px"
                v-model="detailFormData.area_name"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="图标"
              prop="area_icon"
              :label-width="formLabelWidth"
            >
              <el-upload
                class="match_from_uploader"
                :data="uploadData"
                :action="actionUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
              >
                <img
                  v-if="detailFormData.area_icon"
                  :src="detailFormData.area_icon"
                  class="avatar"
                />
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
            <!-- <el-form-item
              label="权限区域值"
              prop="area_mark"
              :label-width="formLabelWidth"
            >
              <el-input
                size="small"
                style="width: 200px"
                v-model="detailFormData.area_mark"
              ></el-input>
            </el-form-item> -->
            <el-form-item
              label="顺序"
              prop="sequence"
              :label-width="formLabelWidth"
            >
              <el-input
                type="number"
                size="small"
                style="width: 200px"
                v-model="detailFormData.sequence"
              ></el-input>
            </el-form-item>
            <el-form-item
              label="备注"
              prop="remark"
              :label-width="formLabelWidth"
            >
              <el-input
                type="textarea"
                :rows="2"
                resize="none"
                style="width: 200px"
                placeholder="请输入内容"
                :autosize="{ minRows: 3, maxRows: 6 }"
                v-model="detailFormData.remark"
              >
              </el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button
              size="small"
              type="primary"
              @click="dialogclose()"
              v-if="dialogBtnKey == 3"
              >确 定</el-button
            >
            <el-button
              size="small"
              v-if="dialogBtnKey != 3"
              @click="dialogclose()"
              >取 消</el-button
            >
            <el-button
              size="small"
              type="primary"
              @click="dialogDetailFormSubmit()"
              v-if="dialogBtnKey != 3 && userType == 0"
              >确 定</el-button
            >
          </span>
        </el-dialog>
      </div>
    </el-row>
  </div>
</template>
<style src="../../assets/css/area/areaManager.css" scoped></style>

<script>
export default {
  name: "AreaManager",
  components: {},
  data() {
    return {
      // userType: localStorage.getItem("type"),
      userType: this.$store.state.loginUserType == "ADMINLOGINUSERCH" ? 0 : 1, // 用户类型;1. 普通; 0. 超级;
      baseAPIUrl: this.$store.state.baseAPIUrl,
      actionUrl: this.$store.state.baseAPIUrl + "/upload/uploadFile", // 上传路径
      uploadData: {
        source: 7,
      }, // 上传额外参数
      headers: {
        Authorization: this.$store.state.loginToken,
      }, // 上传用token
      areaListData: [], // 数据列表
      matchId: "", // 赛事名称id
      matchtitle: "", //赛事名称名称
      currentPage: 1, // 当前页
      pageSizes: [10, 20, 50, 100], // 可选页容量
      pageSize: 10, // 当前页容量
      total: 0, // 总条数
      searchKey: "", // 搜索关键词
      loadingKey: false,
      loadingText: "",
      dialogTitle: "", // 弹窗标题
      dialogBtnKey: "", // 弹窗确认按钮控制; 1. 新增确认;2. 修改确认; 3. 查看
      dialogVisible: false, // 弹窗显示
      detailFormData: {
        id: "",
        area_name: "", // 权限区域名称
        area_icon: "", // 权限区域图标
        area_mark: "", // 权限区域值
        sequence: "", // 顺序
        remark: "", // 备注
      }, // 部门弹窗数据
      detailFormRules: {
        area_name: [
          { required: true, message: "请输入权限区域名称", trigger: "blur" },
          {
            min: 2,
            max: 12,
            message: "长度在 2 到 12 个字符",
            trigger: "blur",
          },
        ],
        area_icon: [
          { required: true, message: "请上传权限区域图标", trigger: "change" },
        ],
        // area_mark: [
        //   { required: true, message: "请输入权限区域值", trigger: "blur" },
        // ],
      },
      formLabelWidth: "90px",
    };
  },
  created: function () {
    let query = this.$route.query;
    if (query.id != undefined && query.id != "") {
      this.matchId = query.id;
    }

    this.getListDataFn();
  },
  methods: {
    // 获取列表数据
    getListDataFn: function () {
      let that = this;
      let url = "/admin/area/index";
      let data = {
        event_id: this.matchId,
        page: this.currentPage,
        perPage: this.pageSize,
        keywords: this.searchKey,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.areaListData = response.list;
            that.total = response.total_count;
            that.matchtitle = response.event.title;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 新增
    addFn: function () {
      let that = this;
      this.dialogTitle = "新增权限区域";
      this.dialogBtnKey = 1;
      this.detailFormData = {
        id: "",
        area_name: "",
        area_icon: "",
        area_mark: "",
        sequence: "",
        remark: "",
      };
      this.$nextTick(function () {
        that.dialogVisible = true;
        that.$refs.dialogDetailForm.clearValidate();
      });
    },
    // 修改
    editFn: function (index, row) {
      this.dialogTitle = "编辑权限区域";
      this.dialogBtnKey = 2;
      this.detailFormData = {
        id: row.id,
        area_name: row.area_name,
        area_icon: row.area_icon,
        area_mark: "",
        sequence: row.sequence,
        remark: row.remark,
      };
      this.$nextTick(function () {
        this.dialogVisible = true;
      });
    },

    // 查看
    detailFn: function (index, row) {
      this.dialogTitle = "查看权限区域";
      this.dialogBtnKey = 3;
      this.detailFormData = {
        id: row.id,
        area_name: row.area_name,
        area_icon: row.area_icon,
        area_mark: "",
        sequence: row.sequence,
        remark: row.remark,
      };
      this.$nextTick(function () {
        this.dialogVisible = true;
      });
    },
    // 弹窗保存
    dialogDetailFormSubmit: function () {
      let that = this;
      let url = "";
      let data = {};
      if (this.dialogBtnKey == 2) {
        url = "/admin/area/update";
        data = {
          id: this.detailFormData.id,
          event_id: this.matchId,
          area_name: this.detailFormData.area_name,
          area_icon: this.detailFormData.area_icon,
          area_mark: "",
          sequence: this.detailFormData.sequence,
          remark: this.detailFormData.remark,
        };
      } else {
        url = "/admin/area/store";
        data = {
          event_id: this.matchId,
          area_name: this.detailFormData.area_name,
          area_icon: this.detailFormData.area_icon,
          area_mark: "",
          sequence: this.detailFormData.sequence,
          remark: this.detailFormData.remark,
        };
      }
      this.$refs.dialogDetailForm.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that
            .$confirm("确认提交?", "提示", {
              confirmButtonText: "确定",
              cancelButtonText: "取消",
            })
            .then(() => {
              that.loadingText = "处理中...";
              that.loadingKey = true;
              that.axios
                .post(url, data)
                .then((response) => {
                  that.loadingKey = false;
                  if (response.code == 0) {
                    if (that.dialogBtnKey == 2) {
                      that.$message.success("修改成功");
                    } else {
                      that.$message.success("新增成功");
                    }
                    that.dialogclose();
                    that.getListDataFn();
                  } else {
                    that.$message.error(response.msg);
                  }
                })
                .catch(function (error) {
                  that.loadingKey = false;
                  console.log(error);
                });
            })
            .catch(() => {});
        }
      });
    },

    // 关闭弹窗
    dialogclose: function () {
      this.dialogVisible = false;
    },

    // 删除
    deleteFn: function (index, row) {
      let that = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        let url = "/admin/area/destroy";
        let data = {
          id: row.id,
        };
        that.loadingText = "处理中...";
        that.loadingKey = true;
        that.axios
          .post(url, data)
          .then((response) => {
            that.loadingKey = false;
            if (response.code == 0) {
              that.$message.success("删除成功");
              let next = that.currentPage - 1;
              if (that.areaListData.length == 1) {
                that.currentPage = next >= 1 ? next : 1;
              }
              that.getListDataFn();
            } else {
              that.$message.error(response.msg);
            }
          })
          .catch(function (error) {
            that.loadingKey = false;
            console.log(error);
          });
      });
    },
    // 页容量改变
    listSizeChange: function (val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getListDataFn();
    },
    // 当前页改变
    listCurrentChange: function (val) {
      this.currentPage = val;
      this.getListDataFn();
    },
    // 搜索按钮
    searchFn: function () {
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 上传成功钩子
    handleAvatarSuccess: function (res, file) {
      this.detailFormData.area_icon = res.image;
      this.$message.success("上传成功");
    },
    // 上传前钩子
    beforeAvatarUpload: function (file) {
      const isJPG = file.type === "image/jpeg";
      const isPNG = file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 3;

      if (!isJPG && !isPNG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
        return false;
      }
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 3MB!");
        return false;
      }
      return true;
    },
  },
};
</script>
